package com.wujige.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wujige.entity.User;
import com.wujige.utils.ClinetUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author: lipan
 * @date: 2021/4/26 21:57
 */

public class DocOperationTest {


    RestHighLevelClient client=null;

    @Before
    public void OpenConection(){
        client= ClinetUtils.getClient();
    }



    /**
     * 测试创建文档
     * @throws Exception
     */
    @Test
    public void testCreateIndex() throws Exception{

        User user=new User();
        user.setAge(20);
        user.setName("张三");
        user.setSex("male");


        ObjectMapper objectMapper=new ObjectMapper();
        String userJson = objectMapper.writeValueAsString(user);


        IndexRequest request=new IndexRequest();
        request.index("user").id("1001");
        request.source(userJson, XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        System.out.println(index.getResult());



    }


    /**
     * 测试更新
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception{

        UpdateRequest updateRequest=new UpdateRequest();

        updateRequest.index("user").id("1001");

        updateRequest.doc(XContentType.JSON,"age",30);

        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(response);
    }


    /**
     * 测试文档查询
     * @throws Exception
     */
    @Test
    public void testQuery() throws Exception{

        GetRequest getRequest=new GetRequest();
        getRequest.index("user").id("1001");

        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

        System.out.println(getResponse.getSourceAsString());
    }


    /**
     * 测试文档删除
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception{



        DeleteRequest request = new DeleteRequest().index("user").id("1003");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
    }

    @After
    public void closeConnection(){
        ClinetUtils.close();
    }
}
